<template>
  <div>
    <img ref="img" :src="src" :style="objectFit">
  </div>
</template>

<script>
const SCHEME_RE = /^([a-z-]+:)?\/\//i
const DATA_RE = /^data:.*,.*/

export default {
  name: "myImage",
  props: {
    src: {
      type: String,
      required: true
    },
    fit: {
      type: String,
      default: 'cover'
    }
  },
  data() {
    return {
      imgSrc: ''
    }
  },
  computed: {
    objectFit() {
      return `--fit:${this.fit}`
    }
  },
  watch: {
    imgSrc: {
      handler(n) {
        this.$nextTick(() => {
          if (n) this.$refs.img.setAttribute('src', n)
        })
      },
      immediate: true
    },
  },
  created() {
    this.initImage()
  },
  methods: {
    initImage() {
      // 网络资源或base64
      if (SCHEME_RE.test(this.src) || DATA_RE.test(this.src) || this.src.indexOf('blob:') === 0) {
        this.imgSrc = this.src
      } else {
        let arr = this.src.split('/')
        const index = arr.findIndex(i => i === 'assets')
        const imgName = arr.slice(index + 1).join('/')
        import('@/assets/' + imgName).then(res => this.imgSrc = res.default)
      }
    }
  }
}
</script>

<style scoped>
img {
  width: 200px;
  height: 200px;
  object-fit: var(--fit);
}
</style>
